package org.example.Server.service.resource;

import lombok.extern.slf4j.Slf4j;
import org.example.Server.mapper.resource.ResourceMapper;
import org.example.Server.model.resource.*;
import org.example.Server.utils.AliOSSUtils;
import org.example.Server.utils.CheckIP;
import org.example.Server.utils.ResultAPI;
import org.example.Server.utils.Upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import static org.example.Server.utils.CommenEnum.NGINX_HTTP;
import static org.example.Server.utils.CommenEnum.VIDEO_COVER;
import static org.example.Server.utils.ExceptionEnum.FFMPEG_ERROR;
import static org.example.Server.utils.ExceptionEnum.SQL_ERROR;

@Service
@Slf4j
public class ResourceService {
    @Autowired
    AliOSSUtils aliOSSUtils;
    @Autowired
    ResourceMapper resourceMapper;

    public ResultAPI getRePersonList(Integer techId, String resourceType) {
        List<ResourceVO> resourceVOS = resourceMapper.getRePersonList(techId, resourceType);
        return ResultAPI.success(resourceVOS);
    }

    public ResultAPI getVideoByTechid(Integer techId, Integer isPass) {
        List<VideoVO> videoList = resourceMapper.getVideoByTechid(techId, isPass);
        return ResultAPI.success(videoList);
    }

    public ResultAPI addResource(ResourceDTO resourceDTO, MultipartFile file) {
        String fileName = file.getOriginalFilename();
        resourceDTO.setResource_name(fileName);
        String url = null;
        try {
            url = aliOSSUtils.upload(file);
        } catch (IOException e) {
            return ResultAPI.error("上传文件失败");
        }
//        String url = Upload.upload(file);
        resourceDTO.setResource_url(url);
        boolean flag = resourceMapper.addResource(resourceDTO);
        if (flag) return ResultAPI.success();
        return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
    }

    public ResultAPI updateResource(ResourceDTO resourceDTO) {
        boolean flag = resourceMapper.updateResource(resourceDTO);
        if (flag) return ResultAPI.success();
        return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
    }

    public ResultAPI deleteResource(Integer resourceId) {
        boolean flag = resourceMapper.deleteResource(resourceId);
        if (flag) return ResultAPI.success();
        return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
    }

    @Transactional(rollbackFor = Exception.class)
    public ResultAPI addvideo(Integer tech_id, MultipartFile file) throws IOException {
        VideoDTO videoDTO = new VideoDTO();
        String fileName = UUID.randomUUID().toString();
        //视频存储url
        String video_url = "";
        //视频封面输出url
        String video_coverOut = "";
        //视频封面地址
        String video_cover = "";
        String[] command = null;

        //获取封面
        if (CheckIP.isLocalIP()) {//本地测试
            //直接将视频换源了
            video_url = aliOSSUtils.upload(file);
            System.out.println(video_url);
            video_coverOut = "G:\\guet_yxch\\" + fileName + ".jpg";
            video_cover = video_coverOut;

            // FFmpeg命令
            command = new String[]{
                    "ffmpeg",
                    "-i",
                    video_url,
                    "-ss", "00:00:01",
                    "-vframes", "1",
                    video_coverOut
            };
        } else {//云服务器运行
            video_url = aliOSSUtils.upload(file);
            System.out.println(video_url);
            video_coverOut = VIDEO_COVER.getContent() + fileName + ".jpg";
            video_cover = NGINX_HTTP.getContent() + "video_cover/" + fileName + ".jpg";
            // FFmpeg命令
            command = new String[]{
                    "ffmpeg",
                    "-i",
                    video_url,
                    "-ss", "00:00:01",
                    "-vframes", "1",
                    video_coverOut
            };
        }
        Process process = null;
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            process = processBuilder.start();
        } catch (IOException e) {
            e.printStackTrace();
            log.info("ffmpeg出错了");
        }

        // 获取命令输出结果
//        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
//        String line;
//        while ((line = reader.readLine()) != null) {
//            log.info("reader.readLine:{}", line);
//        }
        // 等待命令执行完成
        try {
            // 等待进程完成
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                log.info("视频获取封面成功！");
            } else {
                System.out.println("视频获取封面失败: " + exitCode);
                return ResultAPI.error(FFMPEG_ERROR.getResultCode(), FFMPEG_ERROR.getResultMsg());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //视频转码

        //添加视频
        videoDTO.setTech_id(tech_id);
        videoDTO.setResource_url(video_url);
        videoDTO.setVideo_cover(video_cover);
        videoDTO.setResource_name(file.getOriginalFilename());
        videoDTO.setResource_type("video");
        resourceMapper.addResource(videoDTO);
        resourceMapper.addVideo(videoDTO);
        return ResultAPI.success(videoDTO);
    }

    public ResultAPI deletevideo(Integer resource_id) {
        boolean flag = resourceMapper.deleteResource(resource_id);
        if (flag) return ResultAPI.success();
        return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
    }

    public ResultAPI updatevideo(VideoDTO videoDTO) {
        boolean flag = resourceMapper.updateVideo(videoDTO);
        if (flag) return ResultAPI.success();
        return ResultAPI.error(SQL_ERROR.getResultCode(), SQL_ERROR.getResultMsg());
    }

    /**
     * 学生收藏资源
     *
     * @param stuResource
     * @return
     */
    public ResultAPI addStuResource(StuResource stuResource) {
        resourceMapper.addStuResource(stuResource);
        return ResultAPI.success();
    }

    /**
     * 获取学生收藏资源
     *
     * @param userId
     * @param resourceType
     * @return
     */
    public ResultAPI getResourceList(Integer userId, String resourceType) {
        List<StuReVO> stuReVOs = null;
        if (resourceType.equals("video")) {
            stuReVOs = resourceMapper.getStuVideoList(userId);
        } else {
            stuReVOs = resourceMapper.getStuReList(userId, resourceType);
        }
        return ResultAPI.success(stuReVOs);
    }

    public ResultAPI deleteStuResource(List<Integer> ids) {
        resourceMapper.deleteStuResource(ids);
        return ResultAPI.success();
    }
}
